package com.sfpay.coreplatform.order.common.util;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sfpay.coreplatform.order.service.composite.ITask;

public class TaskHandleManger {
	
	private final static Logger logger = LoggerFactory
			.getLogger(TaskHandleManger.class);

	private static TaskHandleManger thm = null;
 
	// 任务消息缓冲队列
	private Queue<ITask> msgQueue = new LinkedList<ITask>();
	 
	// 处理任务线程
	final Runnable handelTask = new Runnable() {
		public void run() {
			while (true) {
				try{
				if (hasMoreAcquire()) {
					
					ITask task = (ITask) msgQueue.poll();
					task.execute();
					 
				}
				}catch(Exception e){
					
					logger.error("asyhandel exception ",e);
				}
			}
		}

	};
	
	 

	//判断消息队列
	private boolean hasMoreAcquire() {
		return !msgQueue.isEmpty();
	}

	//单例
	private TaskHandleManger() {
	}

	public static TaskHandleManger getInstance() {
		if (thm == null) {
			synchronized (TaskHandleManger.class) {
				if (thm == null) {//双重检查
					thm = new TaskHandleManger();					 
					startTaskThread();//启动监控处理线程		
				}
			}
		}
		return thm;
	}
	/**
	 * 启动任务程序
	 */
	public static void startTaskThread(){		
		Thread monitorThread=new Thread(thm.handelTask);
		monitorThread.start();	
	}
	/**
	 * 增加任务
	 * @param task
	 */
	public void addTask(ITask task){
		
		msgQueue.add(task);
	}

}
